require('./utils/mixin');

const logger = wx.getRealtimeLogManager();

App({
  onLaunch: function(options) {
    const { query={}} = options;
    if(query.debug){
      wx.setEnableDebug({
        enableDebug: true
      });
    }

    this.path = options.path;
    this.deviceInfo = wx.getDeviceInfo();
    this.accountInfo = wx.getAccountInfoSync();
    const { miniProgram: { appId, envVersion } } = this.accountInfo;

    this.appId = appId;
    // 正式环境
    if (envVersion === 'release' || options.query.debug_with_release) {
      this.environment = 'pro';
    }
    else{
      this.environment = 'dev';
    }
  },
  getUserInfoNotice: function () {
    return new Promise((resolve, reject) => {
      const random = Math.random();
      if (random > 0.5) {
        resolve();
      } else {
        setTimeout(() => {
          resolve();
        }, 2000);
      }
    });
  },
  // 如果是点击某个地方完成完成操作，但是操作前需要授权
  authorityTap: function (e) {
    return new Promise((resolve, reject) => {
      this.verifyUser(e).then(() => {
        resolve();
      }).catch(() => {
        reject();
      });
    });
  },
  // 用户授权
  verifyUser: function (e, isCatch) {

    return new Promise((resolve, reject) => {
      const { authorization } = this.page.data;

      if(authorization){
        resolve();
      }
      else {

        wx.getUserProfile({
          desc: '用于获取头像和昵称', 
          success: res => {
            console.log(res)
            const { userInfo, encryptedData, iv } = res;

            this.userInfo = Object.assign(this.userInfo || {}, userInfo);
            this.encryptedData = encryptedData;
            this.iv = iv;
    
            this.page.setData({
              authorization: true
            });
            
            resolve();
          },
          fail: err => {
            if (isCatch) {
              reject();
            }
          }
        })
      }
    });
  },
  verifyMobile: function (e) {

    return new Promise((resolve, reject) => {
      // this.getCode().then(code => {

      //   const { detail: { encryptedData, iv } } = e;

      //   if (encryptedData) {
      //     this.encryptedData = encryptedData;
      //     this.iv = iv;

      //     api.mobile({encryptedData, iv, code}).then(res => {
      //       const { result: { data = {}}} = res;
      //       this.userMobile = data;
      //       this.fireEvent('userMobile', data);
      //       resolve();
      //     });
      //   }
      //   else {

      //     if (this.userMobile){
            resolve();
      //     }
      //     else{
      //       wx.hideLoading({});
      //     }
      //   }
      // });
    });
  },
  onPageNotFound(res) {
    console.log(res)
  },
  initLog: function () {
    this.logMsg = wx.getRealtimeLogManager();
    this.logData = {};
  },
  addLog: function (key, params={}, level) {
    const appendLog = function(log, param) {
      for(let p in param) {
        const data = param[p];
        if (log[p]) {
          const list = log[p];
          list.push(data);
          if (list.length > 5) {
            list.shift();
          }
        } else {
          log[p] = [data];
        }
      }
    };
    switch (level) {
      case 'error':
        this.logData.error = this.logData.error || {};
        appendLog(this.logData.error, params);
        break;
      case 'warn':
        this.logData.warn = this.logData.warn || {};
        appendLog(this.logData.warn, params);
        break;
      default:
        this.logData.info = this.logData.info || {};
        appendLog(this.logData.info, params);
    }
  },
  sendLog: function(){
    if (!this.logData) {
      return;
    }
    if (this.logData.info) {
      this.logMsg.info(this.logData.info);
    }
    if (this.logData.warn) {
      this.logMsg.warn(this.logData.warn);
    }
    if (this.logData.error) {
      this.logMsg.error(this.logData.error);
    }
  },
  uploadImg: function (count=9, sourceType=['album', 'camera']) {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count,
        sizeType: ['original'],
        sourceType,
        success: (res) => {
          const files = res.tempFilePaths;

          wx.showLoading({
            icon: 'none',
            title: '上传中...',
          });

          let index = 0;
          const newFiles = [];

          files.forEach(file => {

            wx.uploadFile({
              url: this.isAuzreUpload ? this.uploadUrlAuzre  : this.uploadUrl, 
              filePath: file,
              name: 'file',
              formData: {
                key: file.split('/').pop()
              },
              success: (res) => {
                const data = JSON.parse(res.data);
                const filePath = data.url
                newFiles.push(filePath);
              },
              fail: err => {
                console.log(file + '上传失败');
              },
              complete: res => {
                if(++index === files.length){
                  wx.hideLoading();
                  resolve(newFiles);
                }
              }
            })
          });
        }
      })
    })
  },

  logParams: function(args) {
    const { user } = this;
    const { brand, model, system, platform } = this.deviceInfo;

    if(args[0]){
      args[0] = args[0];
    }

    if(user){
      args = [
        '操作人:' + user.salername + '，',
        '手机号:' + user.mobile + '，',
        '品牌:' + brand + '，',
        '型号:' + model + '，',
        '系统版本:' + system + '，',
        '客户端:' + platform + '，',
        '角色:' + user.role + '，',
        '页面:' + (map[this.page.route] || this.page.route) + '，'
      ].concat(args);
    }

    return args;
  },
  info: function(...args) {
    return logger.info(...this.logParams(args));
  },

  error: function(...args) {
    return logger.error(...this.logParams(args));
  },

  warn: function(...args) {
    return logger.warn(...this.logParams(args));
  },

  setFilterMsg: function(msg) {
    return logger.setFilterMsg(msg);
  },

  addFilterMsg: function(msg) {
    return logger.addFilterMsg(msg);
  }
});
